<template>
  <c-cascader
    v-bind="attrs"
    v-on="$listeners"
    v-model="selfValue"
    v-loading="loading"
    @change="handleChange"
  ></c-cascader>
</template>

<script>
import { cascaderSplit } from '@vimi/utils-tool'

export default {
  props: {
    value: String,
  },
  model: {
    props: 'value',
    event: 'select',
  },
  data() {
    return {
      selfValue: [],
      loading: false,
    }
  },
  computed: {
    productCategoryTree() {
      return this.$store.getters.productCategoryTree
    },
    props() {
      return Object.assign(
        {
          value: 'id',
          label: 'category_name',
          checkStrictly: true,
        },
        this.$attrs.props
      )
    },
    attrs() {
      const { value, ...rest } = this.$attrs
      return Object.assign(
        {
          props: { ...this.props },
          options: this.productCategoryTree,
        },
        rest
      )
    },
  },
  watch: {
    value: {
      handler: function (val) {
        this.initSelfValue(val)
      },
      immediate: true,
    },
  },
  mounted() {
    this.loading = true
    this.$store.dispatch('getProductCategory').finally(() => (this.loading = false))
  },
  methods: {
    initSelfValue(val) {
      ;[, ...this.selfValue] = cascaderSplit(val, [2, 2, 2, 3, 3])
    },
    handleChange(val) {
      const value = val.length ? val[val.length - 1] : ''
      this.$nextTick(() => {
        this.$emit('select', value, this.getLabels())
      })
    },
    getLabels() {
      const nodes = this.getCheckedNodes()
      return nodes.length ? nodes[0].pathLabels : []
    },
    getCheckedNodes() {
      return this.$children[0].getCheckedNodes()
    },
  },
}
</script>
<style lang="scss" scoped></style>
